package com.qvtu.poetry.controller;


import com.qvtu.poetry.entry.Result;
import com.qvtu.poetry.utils.AliOssUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/*
 *  通用接口
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Resource
    private AliOssUtil aliOssUtil;


    //接受文件   MultipartFile  参数名fill应该根前端保持一致

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> uplod(@RequestParam("file") MultipartFile file) {
        log.info("文件上传：", file);
        //将文件上传到阿里云服务器    upoload(getBytes)将文件类型转成文件数组
        try {
            //截取文件名.getOriginalFilename()
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   从最后一个点开始截取
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构成新的文件名
            String objectName = UUID.randomUUID().toString() + extension;

            //得到文件的网址（注：在aliOssUtil已经完成拼接
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);

        } catch (IOException e) {
            log.error("文件上传失败{}", e);
        }
        return Result.error("文件上传失败");
    }
}
